/**
 * Copyright (c) 2019 Coder League
 * All rights reserved.
 *
 * File：IntegralExpireScheduled.java
 * History:
 *         2019年5月30日: Initially created, CJH.
 */
package club.coderleague.ilsp.common.scheduled;

import java.time.Duration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import club.coderleague.ilsp.service.integralrecords.IntegralRecordsService;
import lombok.extern.slf4j.Slf4j;

/**
 * 积分到期任务
 * 
 * @author CJH
 */
@Slf4j
@Component
public class IntegralExpireScheduled {
	/**
	 * 定时任务过期时间
	 */
	@Value("${custom.scheduled.integral.duration}")
	private String duration;
	
	/**
	 * Redis模板
	 */
	private @Autowired RedisTemplate<String, Object> redisTemplate;
	
	/**
	 * Redis保存任务状态key
	 */
	private static final String LOCK_KEY = "integral.expire.scheduled.starttime";
	
	/**
	 * 积分记录Service
	 */
	private @Autowired IntegralRecordsService integralRecordsService;
	
	/**
	 * 定时清理过期积分
	 * 
	 * @author CJH 2019年5月30日
	 */
	@Scheduled(cron = "${custom.scheduled.integral.cron}")
	public void scheduler() {
		try {
			if (redisTemplate.opsForValue().setIfAbsent(LOCK_KEY, System.currentTimeMillis(), Duration.parse(duration))) {
				log.info("开始执行清理过期积分任务...");
				integralRecordsService.updateCleanExpireIntegral();
			} else {
				log.info("清理过期积分任务正在执行中...");
			}
		} finally {
			redisTemplate.delete(LOCK_KEY);
		}
	}
}
